﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PlasmaMes.Services
{
    /// <summary>
    /// Json转换帮助类
    /// </summary>
    public class JsonHelper
    {
        /// <summary>
        /// 任意类型转Json格式
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ObjToJsonString(object obj)
        {
            return JsonConvert.SerializeObject(obj, Formatting.Indented, new JsonSerializerSettings()
            {
                TypeNameHandling = TypeNameHandling.Auto
            });
        }
        /// <summary>
        /// Json格式转任意类型
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="strJson"></param>
        /// <returns></returns>
        public static T JsonStringToObj<T>(string strJson)
        {
            return JsonConvert.DeserializeObject<T>(strJson, new JsonSerializerSettings()
            {
                TypeNameHandling = TypeNameHandling.Auto
            }); ;
        }
        /// <summary>
        /// Json文件转任意类型
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="FilePath"></param>
        /// <returns></returns>
        public static T JsonFileToObj<T>(string FilePath)
        {
            string strJson =  File.ReadAllText(FilePath);
            return JsonConvert.DeserializeObject<T>(strJson, new JsonSerializerSettings()
            {
                TypeNameHandling = TypeNameHandling.Auto
            }); ;
        }
        /// <summary>
        /// 任意类型转Json文件
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="FilePath"></param>
        public static void ObjToJsonFile(object obj, string FilePath)
        {
            string strJson = JsonConvert.SerializeObject(obj, Formatting.Indented, new JsonSerializerSettings()
            {
                TypeNameHandling = TypeNameHandling.Auto
            });
            File.WriteAllText(FilePath, strJson);
        }
    }
}
